"""
Drill-down node - performs dimension drill-down analysis.
"""
from typing import Dict, Any
from ..tools.drill_down import DrillDownAnalyzer
from ..tools.data_loader import DataLoader


def perform_drill_down(state: Dict[str, Any]) -> Dict[str, Any]:
    """
    Perform dimension drill-down analysis.

    Args:
        state: Current state dict

    Returns:
        Updated state dict with drill-down results
    """
    data = state.get('data')
    target_metric = state.get('target_metric', 'revenue')
    dimensions = state.get('dimensions', [])
    config = state.get('config', {})

    if data is None or data.empty or not dimensions:
        state['drill_down_path'] = []
        state['next_action'] = 'decompose_metric'
        return state

    # Initialize tools
    loader = DataLoader()
    analyzer = DrillDownAnalyzer(
        min_contribution_threshold=config.get('min_contribution_threshold', 0.05),
        top_n=config.get('top_n_contributors', 5)
    )

    # Split data into current and baseline periods
    time_range = state.get('time_range')
    baseline_period = state.get('baseline_period')

    current_df, baseline_df = loader.split_by_period(
        data,
        'date',
        time_range,
        baseline_period
    )

    # Get current drill level
    current_level = state.get('current_drill_level', 0)
    max_depth = config.get('max_drill_depth', 3)

    # Initialize drill_down_path if not exists
    if 'drill_down_path' not in state:
        state['drill_down_path'] = []

    try:
        if current_level == 0:
            # First level: find best dimension to drill down
            best_dimension = analyzer.find_best_drill_dimension(
                current_df,
                baseline_df,
                dimensions,
                target_metric
            )

            # Perform drill down
            result = analyzer.drill_down(
                current_df,
                baseline_df,
                best_dimension,
                target_metric,
                level=current_level
            )

            state['drill_down_path'].append(result.dict())
            state['current_drill_level'] = current_level + 1

            # Check if should continue drilling
            if current_level + 1 < max_depth and result.top_contributors:
                top_contrib = result.top_contributors[0]
                if top_contrib.is_significant and abs(top_contrib.contribution) > 0.2:
                    state['should_continue_drill'] = True
                    state['next_action'] = 'drill_down'
                else:
                    state['should_continue_drill'] = False
                    state['next_action'] = 'reasoning'
            else:
                state['should_continue_drill'] = False
                state['next_action'] = 'reasoning'

        else:
            # Multi-level drill down
            # Get the top contributor from previous level
            prev_result = state['drill_down_path'][-1]
            prev_dimension = prev_result['dimension']
            top_value = prev_result['top_contributors'][0]['value']

            # Filter data for the top contributor
            current_filtered = current_df[current_df[prev_dimension] == top_value]
            baseline_filtered = baseline_df[baseline_df[prev_dimension] == top_value]

            # Find remaining dimensions
            remaining_dimensions = [d for d in dimensions if d != prev_dimension]

            if remaining_dimensions and len(current_filtered) > 0:
                best_dimension = analyzer.find_best_drill_dimension(
                    current_filtered,
                    baseline_filtered,
                    remaining_dimensions,
                    target_metric
                )

                result = analyzer.drill_down(
                    current_filtered,
                    baseline_filtered,
                    best_dimension,
                    target_metric,
                    level=current_level,
                    parent_filter={prev_dimension: top_value}
                )

                state['drill_down_path'].append(result.dict())
                state['current_drill_level'] = current_level + 1

                # Check if should continue
                if current_level + 1 < max_depth and result.top_contributors:
                    top_contrib = result.top_contributors[0]
                    if top_contrib.is_significant:
                        state['should_continue_drill'] = True
                        state['next_action'] = 'drill_down'
                    else:
                        state['should_continue_drill'] = False
                        state['next_action'] = 'reasoning'
                else:
                    state['should_continue_drill'] = False
                    state['next_action'] = 'reasoning'
            else:
                state['should_continue_drill'] = False
                state['next_action'] = 'reasoning'

    except Exception as e:
        state['error'] = f"Drill-down analysis failed: {str(e)}"
        state['should_continue_drill'] = False
        state['next_action'] = 'reasoning'

    return state
